package cn.growthgate.fgo.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;

import cn.growthgate.fgo.common.Constants;
import cn.growthgate.fgo.common.base.BaseVo;
import cn.growthgate.fgo.entity.Image;
import cn.growthgate.fgo.service.IImageService;
import cn.growthgate.fgo.util.FileUtils;
import cn.growthgate.fgo.util.ImageUtils;
import cn.growthgate.fgo.util.StringUtils;
import cn.growthgate.fgo.util.UrlUtils;
import cn.growthgate.fgo.web.result.JsonResult;
import cn.growthgate.fgo.web.result.TableResult;

/**
 * 首页Controller
 * 
 * @author GrowthGate
 * @since 2019年1月22日
 *
 */
@Controller
@RequestMapping("/image")
public class ImageController {

	@Autowired
	private IImageService imageService;

	@RequestMapping("/list")
	@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
	public String list() {
		return "image/list";
	}

	@ResponseBody
	@RequestMapping("/tableData")
	@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
	public TableResult<BaseVo<Image>> tableData(Image menu, Integer current, Integer size, String orderByField,
			Boolean isAsc) {
		Wrapper<Image> wrapper = new EntityWrapper<>();

		if (StringUtils.isNotBlank(menu.getUuid())) {
			wrapper.like("uuid", menu.getUuid());
		}
		if (StringUtils.isNotBlank(menu.getName())) {
			wrapper.like("name", menu.getName());
		}
		if (StringUtils.isNotBlank(menu.getEntityName())) {
			wrapper.like("entityName", menu.getEntityName());
		}
		if (menu.getEntityId() != null) {
			wrapper.eq("entityId", menu.getEntityId());
		}

		Page<Image> page = imageService.selectPage(current, size, orderByField, isAsc, wrapper);
		return new TableResult<BaseVo<Image>>(imageService.transformVo(page));
	}

	@ResponseBody
	@RequestMapping("/delete")
	@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
	public JsonResult delete(Long[] ids) {
		List<Long> idList = Arrays.asList(ids);
		List<Image> images = imageService.selectBatchIds(idList);
		// 删除图片
		images.forEach(image -> FileUtils.delete(new File(image.getPath()), true));
		if (imageService.deleteBatchIds(idList)) {
			return JsonResult.ok("删除成功");
		} else {
			return JsonResult.fail("删除失败");
		}
	}

	@RequiresUser
	@ResponseBody
	@RequestMapping("/upload")
	public JsonResult upload(MultipartFile file, HttpServletRequest request) {
		Image image = ImageUtils.uploadImage(file);
		return JsonResult.ok("value", image.getUuid()).set("url",
				request.getContextPath() + ImageUtils.getImageUrl(image));
	}

	@RequestMapping("/{uuid}")
	public void show(@PathVariable String uuid, Integer pixel, Integer width, Integer height, String isBackground,
			HttpServletResponse response) {
		Image image = imageService.getByUUID(uuid);
		// 空图片
		if (image != null) {
			String filename = image.getName();
			response.setHeader("Content-Disposition", "inline;filename*=UTF-8''" + UrlUtils.encode(filename));
			response.setHeader("Cache-Control", "public,max-age=31536000");
			File file = new File(image.getPath());
			try (OutputStream os = response.getOutputStream(); FileInputStream is = new FileInputStream(file);) {
				response.setContentType(FileUtils.getContentType(file));
				if (pixel == null && width == null && height == null) {
					// 原图
					IOUtils.copy(is, os);
				} else {
					// 缩略图（宽高不为空）
					width = width != null ? width : pixel != null ? pixel : height;
					height = height != null ? height : pixel != null ? pixel : width;
					if (StringUtils.isBlank(isBackground)) {
						ImageUtils.scaleToOutputStream(os, file, width, height);
					} else {
						ImageUtils.scaleBackgroundToOutputStream(os, file, width, height);
					}
				}
			} catch (IOException e) {
			}
		}
	}

}
